package com.idea.easy.log.provider;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.lang.Nullable;

/**
 * @className: SpringAware
 * @description:
 * @author: salad
 * @date: 2022/7/2
 **/
@Slf4j
@SuppressWarnings("all")
public class SpringAware implements ApplicationContextAware {

    private static ApplicationContext context;

    public void setApplicationContext(@Nullable ApplicationContext context) throws BeansException {
        SpringAware.context = context;
    }


    public static <T> T getBean(Class<T> clazz) {
        try {
            return clazz == null ? null : context.getBean(clazz);
        }catch (BeansException e){
            return null;
        }
    }

    public static <T> T getBean(String beanName) {
        if(null == beanName || "".equals(beanName.trim()) || !context.containsBean(beanName)) {
            return null;
        }
        try {
            return (T) context.getBean(beanName);
        }catch (BeansException e){
            return null;
        }
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        if (null != beanName && !"".equals(beanName.trim())) {
            return clazz == null ? null : context.getBean(beanName, clazz);
        } else {
            return null;
        }
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static void publishEvent(ApplicationEvent event) {
        if (context != null) {
            try {
                context.publishEvent(event);
            } catch (Exception e) {
                log.error(e.getMessage());
            }

        }
    }

    public static String getAppName() {
        return context.getEnvironment().getProperty("spring.application.name");
    }

    public static String getEnv() {
        if (context != null) {
            String[] activeProfiles = context.getEnvironment().getActiveProfiles();
            return activeProfiles.length > 0 ? activeProfiles[0] : null;
        }
        return null;
    }


}
